package com.platform.cdcs.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.Constant;
import com.sherchen.slidetoggleheader.views.ObservableXListView;
import com.sherchen.slidetoggleheader.views.XListView;
import com.trueway.app.uilib.adapter.EnhancedAdapter;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.tool.Utils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/9/25.
 */
public class TicketProductFragment extends BaseFragment {

    private ItemAdapter itemAdapter;
    private String cusCode, code, time, innoId;
    private int pageIndex = 1;
    private ObservableXListView listView;
    private View allBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        itemAdapter = new ItemAdapter(getContext());
        cusCode = getArguments().getString("cusCode");
        code = getArguments().getString("code");
        time = getArguments().getString("time");
        innoId = getArguments().getString("id");
    }

    @Subscribe
    public void onEventMainThread(RefershEvent event) {
        if (event.mclass == getClass()) {
            pageIndex = 1;
            itemAdapter.clear();
            itemAdapter.notifyDataSetChanged();
            requestProduct(true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initView(View view) {
        initLoadImg(view.findViewById(R.id.load));
        view.findViewById(R.id.activity_main_toolbar).setVisibility(View.GONE);
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        setTitle("出入库单产品");
        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.ticket_header_1, null);
        TextView codeView = (TextView) headerView.findViewById(R.id.code);
        TextView timeView = (TextView) headerView.findViewById(R.id.time);
        codeView.setText(code);
        timeView.setText(time);
        allBtn = headerView.findViewById(R.id.button1);
        allBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                itemAdapter.chooseAll();
                allBtn.setSelected(true);
            }
        });
        TextView btnView = (TextView) view.findViewById(R.id.button1);
        btnView.setText("确定添加");
        btnView.setVisibility(View.VISIBLE);
        btnView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO
                post();
            }
        });
        listView = (ObservableXListView) view.findViewById(android.R.id.list);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                itemAdapter.clear();
                itemAdapter.notifyDataSetChanged();
                requestProduct(false);
            }

            @Override
            public void onLoadMore() {
                requestProduct(false);
            }
        });
        listView.addHeaderView(headerView);
        listView.setAdapter(itemAdapter);
        requestProduct(true);
    }

    @Override
    public int layoutId() {
        return R.layout.listview;
    }

    private void requestProduct(boolean load) {
        if (load) {
            showLoadImg();
        }
        Map<String, String> map = new HashMap<>();
//        map.put("cusCode", cusCode);
//        map.put("inNo", inNo);
        map.put("docNo", code);
//        map.put("pageSize", String.valueOf(Constant.PAGE_SIZE));
//        map.put("pageIndex", String.valueOf(pageIndex));
        getHttpClient().post().url(Constant.NO_INVOICE_PRODUCT).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                listView.stopLoadMore();
                listView.stopRefresh();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                listView.stopLoadMore();
                listView.stopRefresh();
                Type type = new TypeToken<BaseObjResponse<ProductList>>() {
                }.getType();
                BaseObjResponse<ProductList> response = new Gson().fromJson(s, type);
                if ("1".equals(response.getResult().getCode())) {
                    itemAdapter.addAll(response.getResult().getProductList());
                    itemAdapter.notifyDataSetChanged();
                    if (response.getResult().getProductList().size() == Constant.PAGE_SIZE) {
                        listView.setPullLoadEnable(true);
                    } else {
                        listView.setPullLoadEnable(false);
                    }
                } else {
                    Utils.showToast(getContext(), response.getResult().getMsg());
                }
            }
        });
    }

//    private void removeProduct(ProductList.ProductItem item) {
//        showLoadImg();
//        Map<String, String> map = new HashMap<>();
//        map.put("id", item.getId());
//        map.put("inId", id);
//        map.put("docNo", code);
//        getHttpClient().post().url(Constant.CANCEL_INVOICE_PRODUCT).params(Constant.makeParam(map)).build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int i) {
//                dismissLoadImg();
//                Utils.showToast(getContext(), R.string.server_error);
//            }
//
//            @Override
//            public void onResponse(String s, int i) {
//                dismissLoadImg();
//                Type type = new TypeToken<BaseObjResponse<MockObj>>() {
//                }.getType();
//                BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
//                if ("1".equals(response.getResult().getCode())) {
//                    pageIndex = 1;
//                    itemAdapter.clear();
//                    itemAdapter.notifyDataSetChanged();
//                    requestProduct(true);
//                    RefershEvent event = new RefershEvent();
//                    event.mclass = TicketRelationFragment.class;
//                    EventBus.getDefault().post(event);
//                    getActivity().finish();
//                } else {
//                    Utils.showToast(getContext(), response.getResult().getMsg());
//                }
//            }
//        });
//    }
//
//    private void editQty(final ProductList.ProductItem item, final String num) {
//        showLoadImg();
//        Map<String, String> map = new HashMap<>();
//        map.put("inId", item.getId());
//        map.put("qty", num);
//        getHttpClient().post().url(Constant.EDIT_INVOICE_PRODUCTFORAPP).params(Constant.makeParam(map)).build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int i) {
//                dismissLoadImg();
//                Utils.showToast(getContext(), R.string.server_error);
//            }
//
//            @Override
//            public void onResponse(String s, int i) {
//                try {
//                    dismissLoadImg();
//                    Type type = new TypeToken<BaseObjResponse<MockObj>>() {
//                    }.getType();
//                    BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
//                    if ("1".equals(response.getResult().getCode())) {
//                        item.setQty(num);
//                        itemAdapter.notifyDataSetChanged();
//                    } else {
//                        Utils.showToast(getContext(), response.getResult().getMsg());
//                    }
//                } catch (Exception e) {
//
//                }
//            }
//        });
//    }

    private void post() {
        boolean chooseFlag = false;
        String id = "";
        for (int i = 0; i < itemAdapter.getCount(); i++) {
            ProductList.ProductItem item = itemAdapter.getItem(i);
            if (item.isChoose()) {
                chooseFlag = true;
                id = id + item.getId() + ",";
            }
        }
        if (!chooseFlag) {
            Utils.showToast(getContext(), "请先选择!");
            return;
        }
        id = id.substring(0, id.length() - 1);
        showLoadImg();
        Map<String, String> map = new HashMap<>();
//        map.put("cusCode", cusCode);
//        map.put("docNo", code);
        map.put("innoId", innoId);
        //TODO
        map.put("id", id);
        getHttpClient().post().url(Constant.ADD_INVOICE_PRODUCT).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                Type type = new TypeToken<BaseObjResponse<MockObj>>() {
                }.getType();
                BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
                if ("1".equals(response.getResult().getCode())) {
                    Utils.showToast(getContext(), "添加成功");
                    RefershEvent event = new RefershEvent();
                    event.mclass = TicketChooseFragment.class;
                    EventBus.getDefault().post(event);

                    event = new RefershEvent();
                    event.mclass = TicketRelationFragment.class;
                    EventBus.getDefault().post(event);
                } else {
                    Utils.showToast(getContext(), response.getResult().getMsg());
                }
            }
        });
    }

    private class ItemAdapter extends EnhancedAdapter<ProductList.ProductItem> {

        private View.OnClickListener checkListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProductList.ProductItem item = (ProductList.ProductItem) view.getTag();
                item.setChoose(!item.isChoose());
                itemAdapter.notifyDataSetChanged();
                for (ProductList.ProductItem mItem : dataList) {
                    if (!mItem.isChoose()) {
                        allBtn.setSelected(false);
                        return;
                    }
                }
                allBtn.setSelected(true);
            }
        };

        public ItemAdapter(Context context) {
            super(context);
        }

        @Override
        protected void bindView(View paramView, Context paramContext, int position) {
            ViewHolder holder = (ViewHolder) paramView.getTag();
            ProductList.ProductItem item = getItem(position);
            holder.titleView.setText(item.getItemCode());
            holder.timeView.setText(item.getQty() + " " + item.getUom());
            holder.textView.setText(item.getItemName());
            holder.checkView.setSelected(item.isChoose());
            holder.checkView.setTag(item);
        }

        @Override
        protected View newView(Context context, int position, ViewGroup viewgroup) {
            View rootView = inflater.inflate(R.layout.four_item, viewgroup, false);
            ViewHolder holder = new ViewHolder();
            holder.titleView = (TextView) rootView.findViewById(R.id.title);
            holder.titleView.getPaint().setFakeBoldText(true);
            holder.timeView = (TextView) rootView.findViewById(R.id.time);
            holder.textView = (TextView) rootView.findViewById(R.id.text);
            holder.textView.setSingleLine(false);
            holder.checkView = (ImageView) rootView.findViewById(R.id.img);
            holder.checkView.setVisibility(View.VISIBLE);
            holder.checkView.setOnClickListener(checkListener);
            rootView.setTag(holder);
            return rootView;
        }

        public void chooseAll() {
            for (ProductList.ProductItem item : dataList) {
                item.setChoose(true);
            }
            itemAdapter.notifyDataSetChanged();
        }
    }

    private class ViewHolder {
        TextView titleView, timeView, textView;
        ImageView checkView;
    }
}